package com.jianbing.north.system;

import com.jianbing.north.domain.NorthP3DailyDto;
import com.jianbing.north.domain.NorthP3Record;
import com.jianbing.north.domain.NorthPart3Record;
import com.jianbing.north.domain.NorthUserInfo;
import com.jianbing.north.mapper.NorthP3DailyMapper;
import com.jianbing.north.service.INorthAnswerRecordService;
import com.jianbing.north.service.INorthDayPlanService;
import com.jianbing.north.service.INorthPart3RecordService;
import com.jianbing.north.service.INorthUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 * north项目更新用户游戏进度
 * @param
 * @return 
 * @author zheng
 * @create 2024/6/10
 **/

@Component("northUpdateUserProcess")
public class NorthUpdateUserProcess {

    @Autowired
    private INorthUserInfoService northUserInfoService;
    @Autowired
    private INorthAnswerRecordService northAnswerRecordService;
    @Autowired
    private INorthDayPlanService northDayPlanService;

    @Resource
    private NorthP3DailyMapper northP3DailyMapper;
    @Resource
    private INorthPart3RecordService northPart3RecordService;

    private SimpleDateFormat outputFormatter = new SimpleDateFormat("HH:mm:ss");

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Transactional(rollbackFor = Exception.class)
    public void updateAll(){
        List<NorthUserInfo> northUserInfos = northUserInfoService.selectNorthUserInfoList(null);
        int max = northDayPlanService.selectMaxDay();
        for(NorthUserInfo northUserInfo:northUserInfos){
            northUserInfo.setDay(northUserInfo.getDay()+1>max?northUserInfo.getDay():northUserInfo.getDay()+1);
            Long userId = northUserInfo.getUserId();
            Long part2 = northUserInfo.getPart2();
            if(part2==1 || part2 ==2){
                List<Timestamp> time = northAnswerRecordService.getEverydayRightNumByUserIdAndPartAndDifficulty(userId, 2L, part2-1);
                if(time.size()>=5){
                    northUserInfo.setPart2(part2+1);
                } else {
                    if( time.size()>=3 && isThreeDaysAgo(time.get(2))){
                        northUserInfo.setPart2(part2+1);
                    }
                }
            }
            northUserInfoService.updateNorthUserInfo(northUserInfo);
        }
    }

    public void insertP3Daily() {
            NorthPart3Record northPart3Record = new NorthPart3Record();
            // 获取当前日期
            Calendar calendar = Calendar.getInstance();
            // 减去一天
            calendar.add(Calendar.DATE, -1);
            Date yesterday = calendar.getTime();
            logger.info("当前处理日期为 "+yesterday+" 的数据");

            northPart3Record.setInsertTime(yesterday);
            List<NorthPart3Record> recordList = northPart3RecordService.selectP3(northPart3Record);


            for (NorthPart3Record record : recordList) {
                NorthP3DailyDto northP3DailyDto = new NorthP3DailyDto();
                northP3DailyDto.setUserId(record.getUserId());
                northP3DailyDto.setPlayDay(yesterday);
                String[] strings = record.getPath().split(",");
                int flag = 0;
                for (String s : strings) {
                    String[] s1 = s.split(" ");
                    if (s1[0].equals("1")) {
                        flag++;
                    } else if (s1[0].equals("2")) {
                        flag++;
                    } else if (s1[0].equals("3")) {
                        flag++;
                    } else if (s1[0].equals("4")) {
                        flag++;
                    } else if (s1[0].equals("5")) {
                        flag++;
                    }
                }
                List<NorthP3DailyDto> list = northP3DailyMapper.list(northP3DailyDto);
                boolean hasRecordFlag = true;
                NorthP3DailyDto p3DailyDto = new NorthP3DailyDto();
                if (list.size() == 0) {
                    hasRecordFlag = false;
//                    p3DailyDto = list.get(0);
                } else if (list.size()>=1) {
                    p3DailyDto = list.get(0);
                }
                Date duration;
                try {
                    if (p3DailyDto.getPlayDuration() != null) {
                        duration = outputFormatter.parse(longToString(getDuration(record.getBeginTime(), record.getEndTime(), p3DailyDto.getPlayDuration().getTime())));
                    } else {
                        duration = outputFormatter.parse(longToString(getDuration(record.getBeginTime(), record.getEndTime(), 0L)));
                    }
                } catch (ParseException e) {
                    logger.error("处理 NorthPart3Record：" + record + " 的游戏时长出错");
                    continue;
                }
                northP3DailyDto.setPlayDuration(duration);
                if (flag == 5) {
                    northP3DailyDto.setCounts(p3DailyDto.getCounts() == null ? 0 : p3DailyDto.getCounts());
                    northP3DailyDto.setCounts(northP3DailyDto.getCounts() + 1);
                }
                if (hasRecordFlag) {
                    northP3DailyMapper.updateByUserIdAndDay(northP3DailyDto);
                } else {
                    if(northP3DailyDto.getCounts()==null){
                        northP3DailyDto.setCounts(0L);
                    }
                    northP3DailyMapper.insert(northP3DailyDto);
                }
        }
    }


    private Long getDuration(Date begin,Date end,Long playedTime){
        String timeFormat = null;
        Long time = 0L;
        if(begin!=null && end!=null){
            Duration duration = Duration.between(begin.toInstant(),end.toInstant());
            time = duration.getSeconds();
            if(playedTime!=null){
                time += playedTime;
            }
        }
        return time;
    }

    private String longToString(Long time){
        return String.format("%02d:%02d:%02d", time / 3600, (time % 3600) / 60, time % 60);
    }

    private boolean isThreeDaysAgo(Timestamp timestamp){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = sdf.format(timestamp);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.add(Calendar.DATE, -3);//获取3天前的日期对象
        String day1 = sdf.format(calendar1.getTime());//获取3天前的日期
        if(strDate.compareTo(day1)==0){
            return true;
        }else{
            return false;
        }
    }

}
